<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-content">
        <div class="logo">油柑博客</div>
        <nav class="nav">
          <router-link to="/" class="nav-item">首页</router-link>
          <router-link v-for="category in categories" :key="category.id" 
            :to="{ name: 'Category', params: { id: category.id } }" 
            class="nav-item">
            {{ category.name }}
          </router-link>
        </nav>
        <div class="user-actions">
          <router-link to="/login" class="login-btn" v-if="!userInfo.token">登录</router-link>
          <div class="user-info" v-else>
            <span>{{ userInfo.nickname || userInfo.username }}</span>
            <el-dropdown trigger="click">
              <span class="avatar">
                <img :src="userInfo.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'" alt="头像">
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="userInfo.roleId === 1">
                    <router-link to="/admin/articles">后台管理</router-link>
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
    </header>

    <!-- 文章内容区域 -->
    <div class="main-content">
      <div class="article-container">
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="10" animated />
        </div>

        <template v-else>
          <!-- 文章头部 -->
          <div class="article-header">
            <h1 class="article-title">{{ article.title }}</h1>
            <div class="article-meta">
              <div class="meta-item">
                <el-icon><Calendar /></el-icon>
                <span>{{ formatDate(article.createTime) }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Collection /></el-icon>
                <span>{{ article.categoryName }}</span>
              </div>
              <div class="meta-item">
                <el-icon><View /></el-icon>
                <span>{{ article.viewCount }} 阅读</span>
              </div>
            </div>
          </div>

          <!-- 文章内容 -->
          <div class="article-content">
            <div v-html="article.content"></div>
          </div>
          
          <!-- 文章底部 -->
          <div class="article-footer">
            <div class="article-tags" v-if="article.tags && article.tags.length > 0">
              <span class="tag-title">标签:</span>
              <el-tag v-for="tag in article.tags" :key="tag" size="small" effect="light">{{ tag }}</el-tag>
            </div>
            
            <div class="article-actions">
              <el-button type="primary" plain round @click="handleLike">
                <el-icon><ThumbsUp /></el-icon>
                👍点赞 <span v-if="article.likeCount">({{ article.likeCount }})</span>
              </el-button>
              
              <el-button plain round @click="goBack">
                <el-icon><Back /></el-icon>
                返回
              </el-button>
            </div>
          </div>

          <!-- 相关阅读 -->
          <div class="related-articles" v-if="relatedArticles.length > 0">
            <h3 class="section-title">相关阅读</h3>
            <ul class="related-list">
              <li v-for="item in relatedArticles" :key="item.id" class="related-item">
                <router-link :to="{ name: 'Article', params: { id: item.id } }">
                  {{ item.title }}
                </router-link>
                <span class="related-date">{{ formatDate(item.createTime) }}</span>
              </li>
            </ul>
          </div>

          <!-- 评论区域 -->
          <div class="article-comments">
            <h3 class="section-title">评论</h3>
            <div class="comment-form">
              <el-input
                v-model="commentContent"
                type="textarea"
                :rows="4"
                placeholder="请输入您的评论..."
              />
              <div class="form-actions">
                <el-button type="primary" @click="submitComment" :disabled="!commentContent.trim()">
                  提交评论
                </el-button>
              </div>
            </div>
            
            <div class="comment-list" v-if="comments.length > 0">
              <div v-for="comment in comments" :key="comment.id" class="comment-item">
                <div class="comment-avatar">
                  <img :src="comment.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" alt="用户头像">
                </div>
                <div class="comment-content">
                  <div class="comment-header">
                    <span class="comment-author">{{ comment.author }}</span>
                    <span class="comment-time">{{ formatDate(comment.createTime) }}</span>
                  </div>
                  <div class="comment-text">{{ comment.content }}</div>
                  <div class="comment-actions">
                    <span @click="replyToComment(comment)">回复</span>
                  </div>
                </div>
              </div>
            </div>
            <el-empty v-else description="暂无评论" />
          </div>
        </template>
        
        <!-- 返回顶部按钮 -->
        <el-backtop :right="20" :bottom="20" />
      </div>
    </div>

    <!-- 页脚 -->
    <footer class="footer">
      <div class="footer-content">
        <p>&copy; {{ new Date().getFullYear() }} 油柑博客 - 保留所有权利</p>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Calendar, Collection, View, Back } from '@element-plus/icons-vue'
import { getArticleDetail } from '@/api/article'
import { getCategoryList } from '@/api/category'

const route = useRoute()
const router = useRouter()
const article = ref({})
const loading = ref(true)
const comments = ref([])
const relatedArticles = ref([])
const commentContent = ref('')
const categories = ref([])
const userInfo = ref({})

const fetchArticleDetail = async () => {
  try {
    loading.value = true
    const id = route.params.id
    console.log('获取文章详情，ID:', id)
    const res = await getArticleDetail(id)
    article.value = res.data
    
    // 模拟获取评论数据
    setTimeout(() => {
      comments.value = [
        {
          id: 1,
          author: '用户A',
          content: '这篇文章写得很好，学到了很多东西！',
          createTime: '2023-06-15T14:30:00',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        },
        {
          id: 2,
          author: '用户B',
          content: '感谢分享，很有价值的信息。',
          createTime: '2023-06-16T09:15:00',
          avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'
        }
      ]
      
      // 模拟相关文章
      relatedArticles.value = [
        { id: 101, title: '相关推荐：Spring Boot开发实践', createTime: '2023-05-20T10:00:00' },
        { id: 102, title: '相关推荐：Vue.js前端开发技巧', createTime: '2023-05-25T14:00:00' },
        { id: 103, title: '相关推荐：数据库优化方法', createTime: '2023-06-01T09:30:00' }
      ]
    }, 500)
    
  } catch (error) {
    console.error('获取文章详情失败:', error)
    ElMessage.error('获取文章详情失败')
  } finally {
    loading.value = false
  }
}

const fetchCategories = async () => {
  try {
    const res = await getCategoryList()
    categories.value = res.data
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const options = { year: 'numeric', month: 'long', day: 'numeric' }
  return date.toLocaleDateString('zh-CN', options)
}

const goBack = () => {
  router.back()
}

const handleLike = () => {
  if (!article.value.likeCount) {
    article.value.likeCount = 0
  }
  article.value.likeCount++
  ElMessage.success('点赞成功！')
}

const submitComment = () => {
  if (!commentContent.value.trim()) return
  
  const newComment = {
    id: Date.now(),
    author: '当前用户',
    content: commentContent.value,
    createTime: new Date().toISOString(),
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  }
  
  comments.value.unshift(newComment)
  commentContent.value = ''
  ElMessage.success('评论发布成功！')
}

const replyToComment = (comment) => {
  commentContent.value = `@${comment.author} `
}

const handleLogout = () => {
  localStorage.removeItem('user')
  userInfo.value = {}
  ElMessage.success('退出登录成功')
  router.push('/')
}

// 监听路由参数变化，当文章ID变化时重新获取数据
watch(() => route.params.id, (newId, oldId) => {
  if (newId !== oldId) {
    console.log('文章ID变化，重新获取数据:', newId)
    fetchArticleDetail()
    // 滚动到页面顶部
    window.scrollTo(0, 0)
  }
}, { immediate: true })

onMounted(() => {
  fetchArticleDetail()
  fetchCategories()
  userInfo.value = JSON.parse(localStorage.getItem('user') || '{}')
})
</script>

<style scoped>
/* 整体布局 */
.app-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

/* 顶部导航栏 */
.header {
  position: sticky;
  top: 0;
  z-index: 100;
  background-color: #ffffff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  height: 60px;
}

.logo {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.nav {
  display: flex;
  gap: 20px;
}

.nav-item {
  color: #606266;
  text-decoration: none;
  font-weight: 500;
  padding: 8px 0;
  position: relative;
}

.nav-item:hover, .nav-item.router-link-active {
  color: #409EFF;
}

.nav-item::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0;
  height: 2px;
  background-color: #409EFF;
  transition: width 0.3s;
}

.nav-item:hover::after, .nav-item.router-link-active::after {
  width: 100%;
}

.user-actions {
  display: flex;
  align-items: center;
}

.login-btn {
  background-color: #409EFF;
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
  text-decoration: none;
  transition: background-color 0.3s;
}

.login-btn:hover {
  background-color: #66b1ff;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 主体内容 */
.main-content {
  flex: 1;
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

/* 文章容器 */
.article-container {
  max-width: 900px;
  margin: 0 auto;
}

.loading-container {
  padding: 40px 0;
}

/* 文章头部 */
.article-header {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  text-align: center;
}

.article-title {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1.4;
  margin-bottom: 20px;
}

.article-meta {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  color: #909399;
  font-size: 14px;
}

.meta-item {
  display: flex;
  align-items: center;
  margin: 0 15px;
}

.meta-item .el-icon {
  margin-right: 5px;
  font-size: 16px;
}

/* 文章内容 */
.article-content {
  font-size: 16px;
  line-height: 1.8;
  color: #303133;
  margin-bottom: 40px;
}

.article-content :deep(h1),
.article-content :deep(h2),
.article-content :deep(h3),
.article-content :deep(h4) {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

.article-content :deep(h1) {
  font-size: 28px;
}

.article-content :deep(h2) {
  font-size: 24px;
  padding-bottom: 0.3em;
  border-bottom: 1px solid #eaecef;
}

.article-content :deep(h3) {
  font-size: 20px;
}

.article-content :deep(p) {
  margin-bottom: 16px;
}

.article-content :deep(img) {
  max-width: 100%;
  margin: 15px 0;
  border-radius: 4px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.article-content :deep(pre) {
  background-color: #f6f8fa;
  border-radius: 4px;
  padding: 16px;
  overflow: auto;
  margin-bottom: 16px;
}

.article-content :deep(code) {
  font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace;
  padding: 0.2em 0.4em;
  margin: 0;
  font-size: 85%;
  background-color: rgba(27, 31, 35, 0.05);
  border-radius: 3px;
}

.article-content :deep(blockquote) {
  margin: 16px 0;
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
}

/* 文章底部 */
.article-footer {
  margin: 40px 0;
  padding: 20px 0;
  border-top: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

.article-tags {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.tag-title {
  margin-right: 10px;
  font-weight: 500;
}

.article-tags .el-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.article-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

.article-actions .el-button {
  padding: 12px 24px;
}

/* 相关阅读 */
.section-title {
  font-size: 20px;
  font-weight: 600;
  margin: 30px 0 20px;
  color: #303133;
  position: relative;
  padding-left: 15px;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  height: 70%;
  width: 4px;
  background-color: #409EFF;
  transform: translateY(-50%);
}

.related-list {
  list-style: none;
  padding: 0;
}

.related-item {
  padding: 12px 0;
  border-bottom: 1px dashed #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.related-item a {
  color: #606266;
  text-decoration: none;
  transition: color 0.3s;
  flex: 1;
}

.related-item a:hover {
  color: #409EFF;
}

.related-date {
  color: #909399;
  font-size: 13px;
}

/* 评论区 */
.comment-form {
  margin-bottom: 30px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

.comment-list {
  margin-top: 30px;
}

.comment-item {
  display: flex;
  padding: 20px 0;
  border-bottom: 1px solid #ebeef5;
}

.comment-avatar {
  margin-right: 15px;
}

.comment-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  align-items: center;
}

.comment-author {
  font-weight: 500;
  color: #303133;
}

.comment-time {
  font-size: 13px;
  color: #909399;
}

.comment-text {
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
}

.comment-actions {
  margin-top: 10px;
}

.comment-actions span {
  font-size: 13px;
  color: #909399;
  cursor: pointer;
}

.comment-actions span:hover {
  color: #409EFF;
}

/* 页脚 */
.footer {
  background-color: #f4f6f9;
  padding: 20px;
  text-align: center;
  margin-top: 40px;
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  color: #909399;
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    height: auto;
    padding: 10px 20px;
  }

  .nav {
    margin: 10px 0;
    flex-wrap: wrap;
    justify-content: center;
  }

  .user-actions {
    margin-top: 10px;
  }
  
  .article-title {
    font-size: 26px;
  }
  
  .article-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .meta-item {
    margin: 0;
  }
}
</style>